package com.jacobson.huobi.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import com.jacobson.core.widget.logger.LoggerFactory;

import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * @author WuChenZhong on 2019/7/7 22:02
 * @version 1.0.0
 */
public class SoundUtil {
    /**
     * 上下文
     */
    private WeakReference<Context> mContext;

    public void init(Context context) {
        Context ctx = context;
        if (context.getApplicationContext() != null) {
            ctx = context.getApplicationContext();
        }
        this.mContext = new WeakReference<>(ctx);
    }

    /**
     * 播放铃声，不存在的文件使用系统通知铃声
     */
    public void play(String ringtone) {
        Uri notification;
        if (TextUtils.isEmpty(ringtone)) {
            notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        } else {
            try {
                notification = Uri.parse(ringtone);
            } catch (Exception e) {
                notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        }
        Ringtone r = RingtoneManager.getRingtone(mContext.get(), notification);
        r.play();
    }

    public String getRintoneTitle(Context context, String ringtone) {
        Uri notification;
        if (TextUtils.isEmpty(ringtone)) {
            return "system notification";
        } else {
            try {
                notification = Uri.parse(ringtone);
            } catch (Exception e) {
                return "system notification";
            }
        }
        Ringtone r = RingtoneManager.getRingtone(mContext.get(), notification);
        return r.getTitle(context);
    }

    /**
     * 播放声音 不能同时播放多种音频
     * 消耗资源较大
     *
     * @param rawId 音频资源
     */
    public void playSoundByMedia(int rawId) {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);
            try {
                AssetFileDescriptor file = mContext.get().getResources().openRawResourceFd(rawId);
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
//                mediaPlayer.setVolume(0.50f, 0.50f);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private final MediaPlayer.OnCompletionListener beepListener = mediaPlayer -> mediaPlayer.seekTo(0);

    /**
     * 适合播放声音短，文件小
     * 可以同时播放多种音频
     * 消耗资源较小
     */
    public void playSound(int rawId) {
        if (mContext.get() == null) {
            return;
        }
        SoundPool soundPool;
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频的数量
            builder.setMaxStreams(1);
            //AudioAttributes是一个封装音频各种属性的类
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            soundPool = builder.build();
        } else {
            //第一个参数是可以支持的声音数量，第二个是声音类型，第三个是声音品质
            soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        }
        //第一个参数Context,第二个参数资源Id，第三个参数优先级
        soundPool.load(mContext.get(), rawId, 1);
        soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> soundPool1.play(1, 1, 1, 0, 0, 1));
        //第一个参数id，即传入池中的顺序，第二个和第三个参数为左右声道，第四个参数为优先级，第五个是否循环播放，0不循环，-1循环
        //最后一个参数播放比率，范围0.5到2，通常为1表示正常播放
//        soundPool.play(1, 1, 1, 0, 0, 1);
        //回收Pool中的资源
        //soundPool.release();
    }

    private volatile static SoundUtil sInstance;

    private SoundUtil() {
    }

    public static SoundUtil getInstance() {
        if (sInstance == null) {
            synchronized (SoundUtil.class) {
                if (sInstance == null) {
                    sInstance = new SoundUtil();
                }
            }
        }
        return sInstance;
    }
}
